package com.xywy.tangandroid.activity;

import java.util.HashMap;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.xywy.tangandroid.MyApplication;
import com.xywy.tangandroid.R;
import com.xywy.tangandroid.base.BaseActivity;
import com.xywy.tangandroid.bean.User;
import com.xywy.tangandroid.logic.Task;
import com.xywy.tangandroid.util.Constant;
import com.xywy.tangandroid.util.MD5;
import com.xywy.tangandroid.util.SaveLoginPreference;
import com.xywy.tangandroid.util.UIUtil;
import com.xywy.tangandroid.util.UserKeeper;
import com.xywy.tangandroid.vollery.GetRequest;
import com.xywy.tangandroid.vollery.OnVolleyResponseListener;
import com.xywy.tangandroid.vollery.PostRequest;
import com.xywy.tangandroid.vollery.VolleyManager;

public class LoginAct extends BaseActivity {

	private RelativeLayout login_button;
	private RelativeLayout left_img;
	private TextView middle_title;
	// private TextView right_title;
	private LinearLayout tobar;
	private ImageView right_img;
	private TextView forget_password;

	private static int MIN_Count = 6;
	private static int MAX_COUNT = 16;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Task.LOGIN:

				break;
			}
		}
	};
	private EditText login_usename;
	private EditText login_password;

	@Override
	protected void initView(Bundle savedInstanceState) {
		this.setContentView(R.layout.act_login);

		left_img = (RelativeLayout) findViewById(R.id.left_img);
		middle_title = (TextView) findViewById(R.id.middle_title);
		// right_title = (TextView) findViewById(R.id.right_title);
		right_img = (ImageView) findViewById(R.id.right_img);
		middle_title.setText(getResources().getString(R.string.login));
		// right_title.setVisibility(View.VISIBLE);
		// right_title.setText(getResources().getString(R.string.register));

		register = (TextView) findViewById(R.id.regist);

		forget_password = (TextView) findViewById(R.id.forget_password);

		login_usename = (EditText) findViewById(R.id.login_usename);
		login_password = (EditText) findViewById(R.id.login_password);
		login_button = (RelativeLayout) findViewById(R.id.login_button);

		chenck_phone_text = (TextView) findViewById(R.id.chenck_phone_text);
		chenck_phone_img = (ImageView) findViewById(R.id.chenck_phone_img);
		chenck_password_text = (TextView) findViewById(R.id.chenck_password_text);
		chenck_password_img = (ImageView) findViewById(R.id.chenck_password_img);

		
		String[] info=SaveLoginPreference.getParam(context);
		
		login_usename.setText(info[0]);
		login_password.setText(info[1]);
		
		login_usename.addTextChangedListener(mTextWatcher);
		login_usename.setSelection(login_usename.length());

		login_password.addTextChangedListener(PsswordTextWatcher);
		login_password.setSelection(login_password.length());
	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
		middle_title.setOnClickListener(this);
		// right_title.setOnClickListener(this);
		login_button.setOnClickListener(this);
		forget_password.setOnClickListener(this);
		register.setOnClickListener(this);
	}

	@Override
	protected void initData() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.left_img:

			break;
		case R.id.right_title:
			// Intent intent2 = new Intent(this, RegistAct.class);
			// startActivity(intent2);

			break;
		case R.id.forget_password:
			Intent intent1 = new Intent(this, ForgotPasswordAct.class);
			startActivity(intent1);
			break;

		case R.id.login_button:
			// 正常流程
			if (checkInfo())
				login();
			// 测试
//			 User.getIUserInstance().setUserid("46224456");
//			 Intent intent=new Intent(LoginAct.this, FrameAct.class);
//			 startActivity(intent);
//			 finish();
			break;
		case R.id.regist:
			Intent intent2 = new Intent(this, RegistAct.class);
			startActivity(intent2);
			break;
		default:
			break;
		}

	}

	// 登录
	private void login() {
		final String phonenum = login_usename.getText().toString().trim();
		final String password = login_password.getText().toString().trim();
		PostRequest<String> postRequest = new PostRequest<String>(Constant.getUrl(
				"kbb", "users") + "&type=login", String.class,
				new OnVolleyResponseListener<String>() {
					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(context, waittingDialog);
						
						if (response != null) {
							JSONObject object;
							try {
								object = new JSONObject(response);
								int state = object.optInt("state");
								String error = object.optString("error");
								if (state == 200) {
									User.getIUserInstance(context).setUserid(
											object.optString("userid"));
									User.getIUserInstance(context).setBirthday(
											object.optString("birthday"));
									User.getIUserInstance(context).setSex(
											object.optString("sex"));
									User.getIUserInstance(context).setHeight(
											object.optInt("height"));
									User.getIUserInstance(context).setPhonenum(
											object.optString("phonenum"));
									User.getIUserInstance(context).setIsregister(
											object.optString("isregister"));
									User.getIUserInstance(context).setIs_log_sucess(
											true);
									User.getIUserInstance(context).setPassword(
											password);

									System.out.println("打印一下获取的userid"
											+ User.getIUserInstance(context)
													.getUserid());
									
									SaveLoginPreference.saveParam(context, phonenum, password);

									getUserNameFromServer(User.getIUserInstance(
											context).getUserid());
								} else {
									UIUtil.showToast(context, error);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}

					}}

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(context, waittingDialog);
						UIUtil.showToast(context, context.getResources()
								.getString(R.string.network_slow));
					}

				});
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("phonenum", phonenum);// phonenum
		params.put("password", password);// password
		postRequest.setParams(params);
		postRequest.setIsParseJson(false);
		executeRequest(postRequest);

	}

	/**
	 * 获取用户名
	 */
	private void getUserNameFromServer(String userid) {
		try {
			String url = Constant.url
					+ "act=kbb&fun=users&type=pullAccountInfo&tag=wjk&userid="
					+ userid + "&sign="
					+ MD5.md5s(Constant.Sign + Constant.wjkTag);
			Log.e("getnameUrl ", url);
			GetRequest<String> getNameRequest = new GetRequest<String>(url,
					String.class, new OnVolleyResponseListener<String>() {

						@Override
						public void onError(VolleyError volleyError) {
							// TODO Auto-generated method stub
							UIUtil.DissDialog(context, waittingDialog);
							System.out.println(volleyError.getCause());
							Log.e("getuserName-error", volleyError
									.getStackTrace().toString());
						}

						@Override
						public void onSuccess(String response) {
							try {
								UIUtil.DissDialog(context, waittingDialog);
								JSONObject json = new JSONObject(response);
								int state = json.optInt("state");
								if (state == 200) {
									JSONArray array = json
											.optJSONArray("accounts");
									for (int i = 0; i < array.length(); i++) {
										JSONObject item = (JSONObject) array
												.get(i);
										int accountid = item
												.optInt("accountid");
										if (accountid == 0) {
											User.getIUserInstance(context)
													.setAccountstr(
															item.optString("accountstr"));
											UserKeeper.saveUserInfo(
													User.getIUserInstance(context),
													LoginAct.this);
											break;
										}
									}
								}
								Intent intent = new Intent(context,
										FrameAct.class);
								startActivity(intent);
								finish();
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
			getNameRequest.setIsParseJson(false);
			executeRequest(getNameRequest);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private boolean checkInfo() {
		String username = login_usename.getText().toString().trim();

		String password = login_password.getText().toString().trim();
		if (TextUtils.isEmpty(username)) {
			UIUtil.showToast(LoginAct.this,
					getResources().getString(R.string.phonenumber));
			return false;
		} else if (TextUtils.isEmpty(password)) {
			UIUtil.showToast(LoginAct.this,
					getResources().getString(R.string.password));
			return false;
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		VolleyManager.cancelRequest(this);
	}

	/**
	 * 网络出现错误的时候
	 */
	private void doErrorNet() {
		User user = UserKeeper.getCurrentUser(LoginAct.this);
		if (user != null) {
			Intent intent = new Intent(context, FrameAct.class);
			startActivity(intent);
			finish();
		}
	}

	private TextWatcher mTextWatcher = new TextWatcher() {
		private int editStart;
		private int editEnd;
		private CharSequence temp;

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			temp = s;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			editStart = login_usename.getSelectionStart();
			editEnd = login_usename.getSelectionEnd();
			login_usename.removeTextChangedListener(mTextWatcher);
			if (Pattern.matches(Constant.PHONE_MATCH, temp)) {
				chenck_phone_img.setVisibility(View.VISIBLE);
			} else {
				chenck_phone_img.setVisibility(View.GONE);
			}
			if (temp.length() != 0) {
				chenck_phone_text.setVisibility(View.GONE);
			} else {
				chenck_phone_text.setVisibility(View.VISIBLE);
			}

			login_usename.setText(s);
			login_usename.setSelection(editStart);

			login_usename.addTextChangedListener(mTextWatcher);
		}
	};

	private TextWatcher PsswordTextWatcher = new TextWatcher() {
		private int editEnd;
		private int editStart;
		private CharSequence temp;

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			temp = s;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			editStart = login_password.getSelectionStart();
			editEnd = login_password.getSelectionEnd();
			login_password.removeTextChangedListener(PsswordTextWatcher);
			if (Pattern.matches(Constant.PASSWORD, temp)) {
				chenck_password_img.setVisibility(View.VISIBLE);
			} else {
				chenck_password_img.setVisibility(View.GONE);
			}
			if (temp.length() != 0) {
				chenck_password_text.setVisibility(View.GONE);
			} else {
				chenck_password_text.setVisibility(View.VISIBLE);
			}

			login_password.setText(s);
			login_password.setSelection(editStart);

			login_password.addTextChangedListener(PsswordTextWatcher);
		}
	};
	private TextView register;
	private TextView chenck_phone_text;
	private ImageView chenck_phone_img;
	private TextView chenck_password_text;
	private ImageView chenck_password_img;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApplication.getInstance().exit();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
